package com.wjy.mdemo.mvvm;

import android.app.Application;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.view.View;

import com.wjy.mdemo.BR;
import com.wjy.mdemo.bean.UserInfo;
import com.wjy.mdemo.callback.MCallBack;
import com.wjy.mdemo.databinding.ActivityMvvmBinding;

/**
 * created by WangJinyong
 * 业务逻辑处理
 * 数据更新
 */
public class MVVMViewModel extends BaseObservable {

    private ActivityMvvmBinding binding;
    private MVVMModel mvvmModel;
    private String result;
    private String userInput;

    /**
     * 一般需要传入Application对象，方便在ViewModel中使用application
     * 比如SharedPreferences需要使用
     * @param application
     */
    public MVVMViewModel(Application application){
        mvvmModel = new MVVMModel();
    }

    /**
     * getData方法里mvvmModel.getUserInfo需要获取inputName，所以这里再写一个构造方法，把ActivityMvvmBinding传过来，通过binding获取输入框数据
     * @param application
     * @param binding
     */
    public MVVMViewModel(Application application, ActivityMvvmBinding binding){
        mvvmModel = new MVVMModel();
        this.binding = binding;
    }

    public void getData(View view){
//        String inputName = binding.etName.getText().toString();
//        mvvmModel.getUserInfo(inputName, new MCallBack() {
//            @Override
//            public void onSuccess(UserInfo userInfo) {
//                String info = "查询结果：\n"+userInfo.getName()+"|"+userInfo.getAge();
//                setResult(info);
//            }
//
//            @Override
//            public void onFailed() {
//                setResult("查询结果：\n获取信息失败！");
//            }
//        });

        mvvmModel.getUserInfo(userInput, new MCallBack() {
            @Override
            public void onSuccess(UserInfo userInfo) {
                String info = "查询结果：\n"+userInfo.getName()+"|"+userInfo.getAge();
                setResult(info);
            }

            @Override
            public void onFailed() {
                setResult("查询结果：\n获取信息失败！");
            }
        });
    }

    @Bindable
    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
        notifyPropertyChanged(BR.result);
    }

    @Bindable
    public String getUserInput() {
        return userInput;
    }

    public void setUserInput(String userInput) {
        this.userInput = userInput;
        notifyPropertyChanged(BR.userInput);
    }
}
